<template>
  <div class="login-container">
    <div class="login-content">
      <div class="logo-container">
        <img src="@/assets/logo.svg" alt="Logo" class="logo">
        <h1 class="title">个人信息系统</h1>
      </div>
      
      <el-form :model="loginForm" :rules="rules" ref="loginForm" class="login-form">
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="用户名"
            class="apple-input"
            @keyup.enter.native="handleLogin">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password"
            placeholder="密码"
            class="apple-input"
            @keyup.enter.native="handleLogin"
            show-password>
          </el-input>
        </el-form-item>
        <el-form-item class="remember-me">
          <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
          <el-checkbox v-model="loginForm.autoLogin">自动登录</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            @click="handleLogin" 
            class="apple-button">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        <div class="register-link">
          还没有账号？<router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        autoLogin: false
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ]
      },
      loading: false,
      captchaUrl: '/api/captcha',
      isDarkTheme: false,
      loginAttempts: 0,
      maxLoginAttempts: 5,
      lockoutTime: 30 * 60 * 1000 // 30分钟
    }
  },
  created() {
    // 检查是否有保存的登录信息
    const savedLoginInfo = localStorage.getItem('loginInfo')
    if (savedLoginInfo) {
      const { username, password, rememberMe, autoLogin } = JSON.parse(savedLoginInfo)
      this.loginForm.username = username
      this.loginForm.password = password
      this.loginForm.rememberMe = rememberMe
      this.loginForm.autoLogin = autoLogin
      
      if (autoLogin) {
        this.handleLogin()
      }
    }
    
    // 检查是否处于锁定状态
    const lockoutEndTime = localStorage.getItem('lockoutEndTime')
    if (lockoutEndTime && Date.now() < parseInt(lockoutEndTime)) {
      const remainingTime = Math.ceil((parseInt(lockoutEndTime) - Date.now()) / 1000 / 60)
      this.$message.warning(`账号已被锁定，请${remainingTime}分钟后重试`)
    }
  },
  methods: {
    refreshCaptcha() {
      this.captchaUrl = `/api/captcha?t=${new Date().getTime()}`
    },
    async handleLogin() {
      try {
        this.loading = true
        const response = await this.$http.post('/user/login', {
          username: this.loginForm.username,
          password: this.loginForm.password
        })
        
        if (response.data.code === 20000) {
          const { token, user } = response.data.data
          
          // 保存登录信息
          if (this.loginForm.rememberMe) {
            localStorage.setItem('loginInfo', JSON.stringify({
              username: this.loginForm.username,
              password: this.loginForm.password,
              rememberMe: true,
              autoLogin: this.loginForm.autoLogin
            }))
          } else {
            localStorage.removeItem('loginInfo')
          }
          
          // 重置登录尝试次数
          this.loginAttempts = 0
          localStorage.removeItem('lockoutEndTime')
          
          this.$store.dispatch('login', { token, user })
          this.$message.success('登录成功')

          // 根据用户角色决定跳转页面
          if (user.role === 'ADMIN') {
            this.$router.push('/admin/dashboard') // 管理员跳转到管理员首页
          } else {
            this.$router.push('/dashboard') // 普通用户跳转到普通用户首页
          }
        } else {
          this.handleLoginError(response.data.message)
        }
      } catch (error) {
        this.handleLoginError(error.response?.data?.message || '登录失败')
      } finally {
        this.loading = false
      }
    },
    handleLoginError(message) {
      this.loginAttempts++
      
      if (this.loginAttempts >= this.maxLoginAttempts) {
        const lockoutEndTime = Date.now() + this.lockoutTime
        localStorage.setItem('lockoutEndTime', lockoutEndTime.toString())
        this.$message.error(`登录失败次数过多，账号已被锁定30分钟`)
      } else {
        this.$message.error(message || '登录失败')
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('@/assets/background.svg') no-repeat center center;
  background-size: cover;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}

.login-content {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.logo-container {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  font-weight: 500;
  color: #1d1d1f;
  margin: 0;
  letter-spacing: -0.5px;
}

.login-form {
  margin-top: 30px;
}

.apple-input :deep(.el-input__inner) {
  height: 50px;
  border-radius: 12px;
  border: 1px solid #d2d2d7;
  background: rgba(255, 255, 255, 0.8);
  font-size: 16px;
  padding: 0 20px;
  transition: all 0.3s ease;
}

.apple-input :deep(.el-input__inner:focus) {
  border-color: #0071e3;
  box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.1);
}

.apple-button {
  width: 100%;
  height: 50px;
  border-radius: 12px;
  background: #0071e3;
  border: none;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: -0.2px;
  transition: all 0.3s ease;
}

.apple-button:hover {
  background: #0077ed;
  transform: translateY(-1px);
}

.remember-me {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.remember-me :deep(.el-checkbox__label) {
  color: #1d1d1f;
  font-size: 14px;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #1d1d1f;
}

.register-link a {
  color: #0071e3;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-content {
    width: 90%;
    padding: 30px;
  }
  
  .title {
    font-size: 20px;
  }
  
  .apple-input :deep(.el-input__inner) {
    height: 45px;
  }
  
  .apple-button {
    height: 45px;
  }
}
</style> 